package org.example.StudentManagementSystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.example.StudentManagementSystem.common.Result;
import org.example.StudentManagementSystem.service.ClassService;
import org.example.StudentManagementSystem.service.CourseService;
import org.example.StudentManagementSystem.service.TimetableService;
import org.example.StudentManagementSystem.entity.Timetable;
import org.example.StudentManagementSystem.dto.request.TimetableDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Tag(name = "课表管理")
@RequestMapping("/timetable")
@CrossOrigin(origins = "*")
@RestController
public class TimetableController {
    @Autowired
    private TimetableService timetableService;

    @Autowired
    private ClassService classService;

    @Autowired
    private CourseService courseService;

    /**
     * 将Timetable转换为TimetableDTO
     */
    public TimetableDTO convertToDTO(Timetable timetable) {
        TimetableDTO timetableDTO = new TimetableDTO();
        BeanUtils.copyProperties(timetable, timetableDTO);
        if (timetable.getClassId() != null) {
            timetableDTO.setClassName(classService.getById(timetable.getClassId()).getName());
        }
        if (timetable.getCourseId() != null) {
            timetableDTO.setCourseName(courseService.getById(timetable.getCourseId()).getName());
        }
        return timetableDTO;
    }

    /**
     * 获取课表列表
     */
    @Operation(summary = "获取课表列表", description = "分页获取课表列表")
    @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Result.class)), description = "获取课表列表成功")
    @GetMapping("")
    public Result getTimetableList(@Parameter(description = "页码", required = true) @RequestParam(defaultValue = "1") int page,
                                   @Parameter(description = "每页大小", required = true) @RequestParam(defaultValue = "10") int size) {
        Page<Timetable> timetablePage = timetableService.page(Page.of(page, size));
        Page<TimetableDTO> timetableDTOPage = new Page<>();
        List<TimetableDTO> timetableDTOList = timetablePage.getRecords().stream().map(this::convertToDTO).collect(Collectors.toList());
        timetableDTOPage.setRecords(timetableDTOList);
        timetableDTOPage.setCurrent(timetablePage.getCurrent());
        timetableDTOPage.setSize(timetablePage.getSize());
        timetableDTOPage.setTotal(timetablePage.getTotal());
        return Result.success(timetableDTOPage, "获取课表列表成功");
    }

    /**
     * 获取所有课表
     */
    @Operation(summary = "获取所有课表", description = "获取所有课表列表")
    @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Result.class)), description = "获取所有课表成功")
    @GetMapping("/all")
    public Result getAllTimetable() {
        List<Timetable> timetableList = timetableService.list();
        List<TimetableDTO> timetableDTOList = timetableList.stream().map(this::convertToDTO).collect(Collectors.toList());
        return Result.success(timetableDTOList, "获取所有课表成功");
    }

    /**
     * 根据班级获取课程
     */
    @Operation(summary = "根据班级获取课程", description = "分页根据班级ID获取课程")
    @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Result.class)), description = "获取课程成功")
    @GetMapping("/class/{id}")
    public Result getTimetableByClassId(@Parameter(description = "班级ID", required = true) @PathVariable("id") int class_id,
                                        @Parameter(description = "页码", required = true) @RequestParam(defaultValue = "1") int page,
                                        @Parameter(description = "每页大小", required = true) @RequestParam(defaultValue = "10") int size) {
        if (class_id == 0) {
            return Result.error("请选择班级");
        }
        QueryWrapper<Timetable> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_id", class_id);
        Page<Timetable> timetablePage = timetableService.page(Page.of(page, size), queryWrapper);
        List<TimetableDTO> timetableDTOList = timetablePage.getRecords().stream().map(this::convertToDTO).collect(Collectors.toList());
        Page<TimetableDTO> timetableDTOPage = new Page<>();
        timetableDTOPage.setRecords(timetableDTOList);
        timetableDTOPage.setCurrent(timetablePage.getCurrent());
        timetableDTOPage.setSize(timetablePage.getSize());
        timetableDTOPage.setTotal(timetablePage.getTotal());
        return Result.success(timetableDTOPage, "获取课程成功");
    }

    /**
     * 添加课表
     */
    @Operation(summary = "添加课表", description = "添加新的课表")
    @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Result.class)), description = "添加课表成功")
    @PostMapping("")
    public Result addTimetable(@Parameter(description = "课表信息", required = true) @RequestBody Timetable timetable) {
        if (timetable.getNumber() == 0) {
            return Result.error("请输入节次");
        }
        if (timetable.getClassId() == 0) {
            return Result.error("请选择班级");
        }
        if (timetable.getCourseId() == 0) {
            return Result.error("请选择课程");
        }
        if (timetable.getClassTime() == null) {
            return Result.error("请选择上课时间");
        }

        return timetableService.save(timetable) ? Result.success(timetable, "添加课表成功") : Result.error("添加课表失败");
    }

    /**
     * 修改课表
     */
    @Operation(summary = "修改课表", description = "根据ID修改课表")
    @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Result.class)), description = "修改课表成功")
    @PutMapping("/{id}")
    public Result updateTimetable(@Parameter(description = "课表ID", required = true) @PathVariable int id,
                                  @Parameter(description = "新的课表信息", required = true) @RequestBody Timetable timetable) {
        if (timetable.getNumber() == 0) {
            return Result.error("请输入节次");
        }
        if (timetable.getClassId() == 0) {
            return Result.error("请选择班级");
        }
        if (timetable.getCourseId() == 0) {
            return Result.error("请选择课程");
        }
        if (timetable.getClassTime() == null) {
            return Result.error("请选择上课时间");
        }
        timetable.setId(id);
        return timetableService.updateById(timetable) ? Result.success(timetable, "修改课表成功") : Result.error("修改课表失败");
    }

    /**
     * 删除课表
     */
    @Operation(summary = "删除课表", description = "根据ID删除课表")
    @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Result.class)), description = "删除课表成功")
    @DeleteMapping("/{id}")
    public Result deleteTimetable(@Parameter(description = "课表ID", required = true) @PathVariable int id) {
        return timetableService.removeById(id) ? Result.success("删除课表成功") : Result.error("删除课表失败");
    }

}
